<?php

namespace App\Http\Controllers\Backend\Auth;

use App\Http\Controllers\Backend\Controller;
use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
use App\Services\Auth\ModuleService;
use App\Entities\Auth\Module;

class ModuleController extends Controller
{
    protected $services;

    public function __construct(ModuleService $service)
    {
        $this->baseViewAddress = 'backend.auth.module.';
        $this->service = $service;
    }

    public function list()
    {
        return response()->json($this->service->getPageList());
    }

    public function tree()
    {
        $data = $this->service->getTree();

        return response()->json($data);
    }

    public function index()
    {
        return View::make($this->baseViewAddress.'index');
    }

    /**
     * 添加模块视图.
     *
     * @return void
     */
    public function create()
    {
        $module = new Module();

        return View::make($this->baseViewAddress.'create', compact('module'));
    }

    /**
     * 添加模块.
     *
     * @param Request $request
     *
     * @return void
     */
    public function store(Request $request)
    {
        if ($this->service->create($request->all())) {
            return redirect(route('admin.auth.module.index'))->with(['status' => '添加成功']);
        }

        return redirect(route('admin.auth.module.index'))->with(['status' => '系统错误']);
    }

    public function show($id)
    {
        $module = $this->service->show($id);

        return View::make($this->baseViewAddress.'show', compact('module'));
    }

    public function edit($id)
    {
        $module = $this->service->show($id);

        return View::make($this->baseViewAddress.'edit', compact('module'));
    }

    public function update(Request $request, $id)
    {
        if ($this->service->update($id, $request->all())) {
            return redirect(route('admin.auth.module.index'))->with(['status' => '更新成功']);
        }

        return redirect(route('admin.auth.module.index'))->withErrors(['status' => '系统错误']);
    }

    /**
     * 删除模块.
     *
     * @param Request $request
     *
     * @return void
     */
    public function destroy()
    {
        $ids = request()->get('ids');

        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        $result = $this->service->remove($ids);
        if ($result['flag']) {
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return response()->json(['code' => 1, 'msg' => $result['message'] ? $result['message'] : '系统错误']);
        }
    }
}
